'use server';

import { prisma } from 'src/lib/prisma';
import { Session, withAuth } from './auth';

async function _getFolderListByParentId(session: Session, parentId: string | null) {
  const folderList = await prisma.folder.findMany({
    where: {
      userId: session.userId,
      parentId, // 根目录传 null
    },
  });

  return folderList;
}
/**
 * 获取用户资源文件夹列表
 * @param parentId 父级文件夹 ID，不传获取根目录下的文件夹
 */
export const getFolderListByParentId = withAuth(_getFolderListByParentId);

async function _getFolderPathById(session: Session, folderId?: string) {
  if (!folderId) {
    return [];
  }
  const folder = await prisma.folder.findUnique({
    where: {
      userId: session.userId,
      id: folderId,
    },
  });

  if (!folder) {
    throw new Error('文件夹不存在或无权访问');
  }

  // 用于存储路径的数组
  const pathArray = [];
  let currentFolder: typeof folder | null = folder;

  // 递归向上查找父文件夹，直到找到根文件夹（parentId 为 null）
  while (currentFolder) {
    pathArray.unshift(currentFolder); // 将当前文件夹添加到路径数组的开头

    if (!currentFolder.parentId) {
      break; // 如果没有父文件夹，说明已经到达根目录
    }

    // 查询父文件夹
    currentFolder = await prisma.folder.findUnique({
      where: {
        id: currentFolder.parentId,
      },
    });
  }

  return pathArray;
}
/**
 * 获取用户资源文件夹路径
 * @param folderId 文件夹 ID
 */
export const getFolderPathById = withAuth(_getFolderPathById);

async function _createFolder(
  session: Session,
  params: {
    name: string;
    parentId?: string;
    description?: string;
  }
) {
  const { name, parentId, description } = params;
  const firstFolder = await prisma.folder.findFirst({
    where: {
      name,
      userId: session.userId,
      parentId,
    },
  });
  if (firstFolder) {
    throw new Error('当前目录下的文件夹重名');
  }
  const folder = await prisma.folder.create({
    data: {
      name,
      userId: session.userId,
      parentId,
      description,
    },
  });
  return folder;
}
/**
 * 创建用户资源文件夹
 * @param name 文件夹名称
 * @param parentId 父级文件夹 ID
 */
export const createFolder = withAuth(_createFolder);

async function _getFolderInfoById(session: Session, folderId: string) {
  if (!folderId) {
    return null;
  }
  
  const folder = await prisma.folder.findUnique({
    where: {
      id: folderId,
      userId: session.userId,
    },
    include: {
      _count: {
        select: {
          images: true,
        },
      },
    },
  });

  if (!folder) {
    return null;
  }

  // 获取文件夹中所有图片的文件大小总和
  const totalSizeResult = await prisma.image.aggregate({
    where: {
      folderId: folderId,
    },
    _sum: {
      fileSize: true,
    },
  });

  const { _count, ...restInfo } = folder;

  return {
    ...restInfo,
    imageCount: _count.images,
    totalFileSize: totalSizeResult._sum.fileSize || 0,
  };
}
/**
 * 获取用户资源文件夹信息
 * @param folderId 文件夹 ID
 */
export const getFolderInfoById = withAuth(_getFolderInfoById);
